<template>
  <div class="main device-right-container">
    <header class="header-container">
      <div class="title"><span>监控设备列表</span></div>
    </header>
    <div class="chart-box">
      <div class="double">
        <div class="row">
          <div v-for="room in roomsCom" :class="{'col-24': room.tubesCount === 4 || router === 2, 'col-12': room.tubesCount === 2}" class="mt10 row-padding">
            <state
              :data="room"
              @showchart="onShowChart"
              @showWorkedChart="onShowWorkedChart">
            </state>
          </div>
        </div>
      </div>
    </div>
    <!-- 模态窗口 -->
    <modal v-if="showChart" @close="showChart = false">
      <div class="chart-content">
        <div class="chart-title">
          <span>{{ chartTitle }}</span>
        </div>
        <div class="btn-box">
          <botton-group :btns="chartBtns" :selected="selectedChartBtn"@click="onToggleChartDate"></botton-group>
        </div>
        <Bar width="700px" height="300px" :options="chartOptions"></Bar>
        <div class="close-btn" @click="showChart = false">
          <!--<i class="fa fa-times"></i>-->
        </div>
      </div>
    </modal>
    <!-- 模态窗口 -->
    <modal v-if="showWorkedChart" @close="showWorkedChart = false">
      <div class="chart-content">
        <div class="chart-title">
          <span>{{ chartTitle }}</span>
        </div>
        <div class="btn-box">
          <div class="btn-box-online">在线率</div>
        </div>
        <Bar width="700px" height="300px" :options="chartWorkOptions"></Bar>
        <div class="modal-bottom-box">
          <div>在线率:<span class="modal-bottom-box-online">{{charWorkedStatistics}}</span>%</div>
        </div>
        <div class="close-btn" @click="showWorkedChart = false">
          <!--<i class="fa fa-times"></i>-->
        </div>
      </div>
    </modal>
  </div>
</template>

<script>
import State from './State'
import api from 'api'
import formatDate from 'filters/format-date'
import axios from 'axios'

export default {
  name: 'DeviceList',

  components: {
    State
  },

  data () {
    return {
      rooms: [],
      path: this.$route.path,
      showChart: false,
      showWorkedChart: false,
      rowHeight: 70,
      show: false,
      chartDeviceMsg: {},
      chartTitle: '',
      psumHistorys: [],
      selectedChartBtn: {},
      chartLimit: {},
      chartBtns: [
        {
          name: '24小时',
          value: 1
        },
        {
          name: '7天',
          value: 7
        },
        {
          name: '15天',
          value: 15
        }
      ],
      chartWorkedBtns: [
        {
          name: '在线率'
        },
        {
          name: '运行率'
        }
      ],
      deviceStatus: ''
    }
  },

  computed: {
    min () {
      let res = _.minBy(this.psumHistorys, (item) => {
        return item['27']
      })
      if (res) {
        return res['27']
      }
      return 0
    },
    max () {
      let res = _.maxBy(this.psumHistorys, (item) => {
        return item['27']
      })
      if (res) {
        return res['27']
      }
      return 2
    },
    router () {
      return this.$route.path.split('/')[1] === ':0' ? 1 : 2
    },
    chartOptions () {
      let chartOptions = {
        grid: {
          containLabel: true,
          left: '3%',
          right: '3%',
          bottom: '10%',
          top: '10%'
        },
        legend: {
          align: 'left',
          right: 0,
          top: 0,
          orient: 'horizontal',
          textStyle: {
            color: '#fff'
          }
        },
        tooltip: {
          padding: 10,
          formatter: '时间:  {b}<br />管压:  {c}'
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          data: this.toChartDate(this.psumHistorys.map(item => item['snapshot_date'])),
          name: '管压正常值范围（ 0.85 - 1.25Mpa）',
          nameLocation: 'middle',
          nameGap: 30
        }],
        yAxis: [{
          type: 'value',
          min: Math.floor((this.chartLimit.min > this.min ? this.min : this.chartLimit.min) * 10) / 10,
          max: Math.ceil((this.chartLimit.max < this.max ? this.max : this.chartLimit.max) * 10) / 10
        }],
        series: [{
          name: '管压',
          type: 'line',
          symbolSize: 6,
          itemStyle: {
            normal: {
              color: '#75a084'
            }
          },
          data: this.psumHistorys.map(item => item['27'] || 0),
          markLine: {
            data: [[{
              symbol: 'none',
              coord: [0, this.chartLimit.min]
            }, {
              symbol: 'none',
              coord: [this.psumHistorys.length - 1, this.chartLimit.min],
              name: '最小水压' + this.chartLimit.min + 'Mpa',
              label: {
                normal: {
                  show: 'none',
                  formatter: ' '
                }
              }
            }], [{
              symbol: 'none',
              coord: [0, this.chartLimit.max]
            }, {
              symbol: 'none',
              coord: [this.psumHistorys.length - 1, this.chartLimit.max],
              name: '最大水压' + this.chartLimit.max + 'Mpa',
              label: {
                normal: {
                  show: 'none',
                  formatter: ' '
                }
              }
            }]]
          }
        }]
      }
      return chartOptions
    },
    chartWorkOptions () {
      let chartWorkedOptions = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: []
        },
        grid: {
          left: '5%',
          right: '7%',
          bottom: '30%',
          top: '30%',
          containLabel: true
        },
        toolbox: {
        },
        xAxis: [{
          type: 'category',
          data: this.toChartDate(this.sortChart(this.psumHistorys.map(item => item['create_time'] || 0).reverse()))
        }],
        yAxis: [{
          type: 'value',
          min: 0,
          max: 1,
          interval: 1,
          axisLabel: {
            formatter: function (value, index) {
              // 格式化成月/日，只在第一个刻度显示年份
              return value === 1 ? '在线' : '离线'
            }
          }
        }],
        series: [
          {
            name: '状态',
            type: 'line',
            step: 'start',
            markLine: {
              silent: true,
              symbol: 'none',
              data: [
                {
                  yAxis: this.deviceStatus
                }
              ]
            },
            itemStyle: {
              normal: {
                color: '#29aaaa'
              }
            },
            data: this.sortChart(this.psumHistorys.map(item => item['status'] || 0)).reverse()
          }
        ]
      }
      return chartWorkedOptions
    },
    roomsCom () {
      let res = []
      if (!this.rooms || !this.rooms.length) {
        return res
      }
      let level = this.$store.getters.level
      let waterTempHumidity = this.$store.getters.waterTempHumidity
      let flooding = this.$store.getters.flooding
      // 将数据对比vuex中拿到的数据分散入每一个组件
      this.rooms.forEach(element => {
        // 传入初始值
        element['level'] = []
        element['waterTempHumidity'] = {'13': '-', '14': '-'}
        element['flooding'] = {'25': '-'}
        level.forEach(item => {
          if (element.title === item.room) {
            element['level'].push(item.data)
          }
        })
        waterTempHumidity.forEach(item => {
          if (element.title === item.room) {
            element['waterTempHumidity'] = item.data
          }
        })
        flooding.forEach(item => {
          if (element.title === item.room) {
            element['flooding'] = item.data
          }
        })
        element['tubesCount'] = _.filter(element.devices, (ite) => {
          return ite.type === 3
        }).length
      })
      // 保证v-for的监听（v-for的监听对数组操作方法(push,concat)有监听,直接去改变其数组的某一个变量是没有监听的）
      return _.cloneDeep(this.rooms)
    },
    // 对在线率进行统计
    charWorkedStatistics () {
      let onlineNumber = 0
      let arr = this.psumHistorys.map(item => item['status'] || 0)
      arr.forEach(item => {
        if (item === 1) {
          onlineNumber++
        }
      })
      if (arr.length === 0) {
        return 0
      } else {
        return parseInt(onlineNumber / arr.length * 100)
      }
    }
  },

  mounted () {
    this.$nextTick(() => {
      this.show = true
    })
    this.getRooms()
    this.requestRestfulData()
  },

  methods: {
    getRooms () {
      axios.get('static/data/devices/water.json').then((res) => {
        switch (this.$route.path.split('/')[1]) {
          case ':0':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
          case ':1':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '香槟'
            })
            break
          case ':2':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
          case ':3':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
        }
      }).catch((err) => {
        this.handleError(err)
      })
    },
    onToggleChartDate (btn) {
      this.selectedChartBtn = btn
      this.psumHistorys = []
      this.getChartData()
    },
    toChartDate (dateArr) {
      let result = []
      dateArr.forEach((date) => {
        let resultDate = formatDate(date, 'MM-dd hh:mm')
        result.push(resultDate)
      })
      // let now = formatDate(new Date(), 'MM-dd hh:mm')
      // result.push(now)
      return result
    },
    // 对返回来的时间做排序
    sortChart (data) {
      return _.sortBy(data, function (item) { return item['create_time'] || 0 })
    },
    initChart () {
      this.selectedChartBtn = this.chartBtns[0]
    },
    getChartData () {
      let { productId, deviceId } = this.chartDeviceMsg
      let day = this.selectedChartBtn.value || 1
      let params = {
        'offset': 0,
        'limit': 2500,
        'date': {
          'begin': new Date() - day * 1000 * 60 * 60 * 24,
          'end': +new Date()
        },
        'rule_id': '58d0990cc5740e446cc94655'
      }
      api.snapshot.getSnapshot(productId, deviceId, params).then((res) => {
        this.psumHistorys = res.data.list
      }).catch((res) => {
        this.handleError(res)
      })
    },
    // 获得设备历史在线数据
    getCharWorkedtData () {
      let { productId, deviceId } = this.chartDeviceMsg
      // let day = this.selectedChartBtn.value || 1
      let params = {
        'offset': 0,
        'limit': 24,
        'query': {
          'device_id': deviceId,
          'product_id': productId
        }
      }
      api.device.getRecords(params).then((res) => {
        this.psumHistorys = res.data.list
      }).catch((res) => {
        this.handleError(res)
      })
    },
    onResize () {
    },
    onShowChart (deviceMsg, chartTitle, limit) {
      this.initChart()
      this.chartDeviceMsg = deviceMsg
      this.chartTitle = chartTitle
      this.chartLimit = limit
      this.getChartData()
      this.showChart = true
    },
    onShowWorkedChart (deviceMsg, chartTitle, limit) {
      this.initChart()
      this.chartDeviceMsg = deviceMsg
      this.chartTitle = '近期设备在线概况'
      this.deviceStatus = deviceMsg.chartDeviceMsg
      this.getCharWorkedtData()
      // this.chartOptions = chartOptions
      this.showWorkedChart = true
    },
    requestRestfulData () {
      this.$store.dispatch('updateWaterDeviceStatus', this)
    }
  },
  watch: {
    // 当路由发生改变时候,针对于从天悦排水转到香槟排水
    router: function () {
      axios.get('static/data/devices/water.json').then((res) => {
        switch (this.$route.path.split('/')[1]) {
          case ':0':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
          case ':1':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '香槟'
            })
            break
          case ':2':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
          case ':3':
            this.rooms = _.filter(res.data, (item) => {
              return item.area === '天悦'
            })
            break
        }
      }).catch((err) => {
        this.handleError(err)
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../../../assets/stylus/base'

.row-padding {
  padding: 0 0 0 10px;
  box-sizing: border-box;
}

.device-right-container {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  font-size: 12px;

  .title {
    height 50px
    line-height 50px
    font-size 14px
    margin-left: 10px;
  }

  .chart-box {
    width: 100%;
    position:absolute;
    top:50px;
    bottom:0px;
    padding: 0 20px 0 5px;
    over-flow:hidden;
    .double{
      width:100%;
      height: 100%;
      padding-right:50%;
      overflow: auto;
    }
  }

  .triangle {
    triangle(#fff, 10px);
    margin-left: 5px;
  }

  .chart-content {
    position relative
    width 100%
    height 100%
    background #1e1e1e

    .chart-title {
      color #ccc 
      height 50px
      line-height 50px
      font-size 14px
      padding-left 20px
    }

    .btn-box {
      text-align center
      position relative
      z-index 1000
    }
    .modal-bottom-box {
      position absolute
      bottom 30px
      width 100%
      text-align center
      color #ccc
      .modal-bottom-box-online {
        font-size 14px
      }
    }

    .close-btn {
      background:url('../../../../assets/images/u508.png') no-repeat center center
      position absolute
      right 0
      top 0
      width 40px
      height 40px
      font-size 25px
      text-align center
      cursor pointer
      opacity 0.5
    }
  }
}
.btn-box-online
  background #3c3a3a
  width 50px
  line-height 30px
  margin-right 1px
  display inline-block
  padding 0 7px
  text-align center
  &:hover
    background #3c3a3a
    color #fff        
  &.selected
    background #434343
    color #fff
</style>
